/**create by liuhua at 2020年10月20日 下午2:47:56**/
package com.star.aries.controller;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import javax.validation.Valid;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.star.aries.dto.BaseResult;
import com.star.aries.dto.req.ExportStudentRequestDto;
import com.star.aries.dto.res.StudentResponseDto;
import com.star.aries.utils.DateUtils;
import com.star.aries.utils.ExcelUtils;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "Excel")
@RestController
public class ExcelController {
  
  @RequestMapping(value = "/export", method = RequestMethod.POST)
  @Operation(summary = "导出-test", method = "POST" )
  public ResponseEntity<byte[]> exportExcel(@Valid @RequestBody ExportStudentRequestDto param) {
    List<String> includeFiled = Optional.ofNullable(param).map(ExportStudentRequestDto::getFields).map(x -> Arrays.asList(x.split(","))).orElse(null);
    List<StudentResponseDto> students = new ArrayList<>();
    LocalDateTime now = LocalDateTime.now();
    StudentResponseDto stu1 = StudentResponseDto.builder().id(1L).name("张三").sex(1).age(18).birth(DateUtils.toLocalDate("1992-01-01", "yyyy-MM-dd")).createTime(now).build(); 
    StudentResponseDto stu2 = StudentResponseDto.builder().id(2L).name("李四").sex(0).age(19).birth(DateUtils.toLocalDate("1991-01-01", "yyyy-MM-dd")).createTime(now).build(); 
    StudentResponseDto stu3 = StudentResponseDto.builder().id(3L).name("王五").sex(0).age(20).birth(DateUtils.toLocalDate("1990-01-01", "yyyy-MM-dd")).createTime(now).build(); 
    StudentResponseDto stu4 = StudentResponseDto.builder().id(4L).name("赵六").sex(1).age(18).birth(DateUtils.toLocalDate("2020-10-29", "yyyy-MM-dd")).createTime(now).build(); 
    students.add(stu1);
    students.add(stu2);
    students.add(stu3);
    students.add(stu4);
    try {
		return ExcelUtils.exportExcel("学生信息", students, StudentResponseDto.class, includeFiled);
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	return null;
  }
  
  @RequestMapping(value = "/import", method = RequestMethod.POST)
  @Operation(summary = "导入-test", method = "POST" )
  public BaseResult<List<StudentResponseDto>> importExcel() {
    String file = "f:/abe.xlsx";
    List<StudentResponseDto> list = ExcelUtils.importExcel(file, StudentResponseDto.class);
    return BaseResult.success(list);
  }
}
